package com.cxliu.cnews.Weather.Presenter;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;

import com.cxliu.cnews.Weather.Api.ApiManager;
import com.cxliu.cnews.Weather.Bean.LocationBean;
import com.cxliu.cnews.Weather.Bean.WeatherBean;
import com.cxliu.cnews.Weather.View.IWeatherView;

import java.util.List;

/**
 * Created by liuchenxu on 2016/8/2.
 */
public class WeatherImpl implements WeatherPresenter {

    private IWeatherView mIWeatherView;

    @Override
    public void getLocationInfo(Context context) {
        LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            mIWeatherView.getLocationFail();
        }
        Location location=manager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        if(location!=null){
            double latitude = location.getLatitude();//经度
            double longitude = location.getLongitude();//纬度
            ApiManager.getLocationInfo(latitude+"",longitude+"",new ApiManager.LocationApiInterface(){

                @Override
                public void onSuccess(LocationBean bean) {
                    getWeatherInfo(bean.getResult().getAddressComponent().getCity());
                    mIWeatherView.setCity(bean.getResult().getAddressComponent().getCity());
                }

                @Override
                public void onFail() {
                    getWeatherInfo("南京");
                    mIWeatherView.setCity("南京");
                    mIWeatherView.getLocationFail();
                }
            });
        }
        else{
            mIWeatherView.setCity("南京");
            getWeatherInfo("南京");
//            mIWeatherView.getLocationFail();
        }
    }

    /**
     * 根据地理位置获取天气信息
     * @param cityname
     */
    @Override
    public void getWeatherInfo(final String cityname) {
        ApiManager.getWeatherInfo(cityname, new ApiManager.WeatherApiInterface() {
            @Override
            public void onSuccess(List<WeatherBean> beans) {
                mIWeatherView.loadWeatherInfo(beans);
            }

            @Override
            public void onFail() {
                mIWeatherView.getWeatherInfoFail();
            }
        });
    }

    public WeatherImpl(IWeatherView view){
        if(view!=null){
            mIWeatherView=view;
        }
    }
}
